In [14]:
from numpy import sin, linspace, pi
from pylab import plot, show, title, xlabel, ylabel, subplot
from scipy import fft, arange
%matplotlib inline
In [15]:
def plotSpectrum(y,Fs):
"""
Plots a Single-Sided Amplitude Spectrum of y(t)
source: http://glowingpython.blogspot.com/2011/08/how-to-plot-frequency-spectrum-with.html
"""
n = len(y) # length of the signal
k = arange(n)
T = n/Fs
frq = k/T # two sides frequency range
frq = frq[range(n/2)] # one side frequency range
Y = fft(y)/n # fft computing and normalization
Y = Y[range(n/2)]
plot(frq,abs(Y),'r') # plotting the spectrum
xlabel('Freq (Hz)')
ylabel('|Y(freq)|')
In [16]:
Fs = 150.0; # sampling rate
Ts = 1.0/Fs; # sampling interval
t = arange(0,1,Ts) # time vector
ff = 5; # frequency of the signal
y = sin(2*pi*ff*t)
In [17]:
subplot(2,1,1)
plot(t,y)
xlabel('Time')
ylabel('Amplitude')
subplot(2,1,2)
plotSpectrum(y,Fs)
show()
You should see a spike at each ff you added in
In [34]:
Fs = 150.0; # sampling rate
Ts = 1.0/Fs; # sampling interval
t = arange(0,1,Ts) # time vector
y2 = sin(2*pi*8*t)
In [42]:
subplot(2,1,1)
plot(t,y2)
xlabel('Time')
ylabel('Amplitude')
subplot(2,1,2)
plotSpectrum(y2,Fs)
show()
In [36]:
y3 = y + y2
In [43]:
subplot(2,1,1)
plot(t,y3)
xlabel('Time')
ylabel('Amplitude')
subplot(2,1,2)
plotSpectrum(y3,Fs)
show()
In [40]:
y4 = y * -1
In [44]:
subplot(2,1,1)
plot(t,y4)
xlabel('Time')
ylabel('Amplitude')
subplot(2,1,2)
plotSpectrum(y4,Fs)
show()
In [53]:
y5 = sin(2*pi*14*t)
In [54]:
subplot(2,1,1)
plot(t,y5)
xlabel('Time')
ylabel('Amplitude')
subplot(2,1,2)
plotSpectrum(y5,Fs)
show()
In [55]:
y6 = y5 + y3
In [56]:
subplot(2,1,1)
plot(t,y6)
xlabel('Time')
ylabel('Amplitude')
subplot(2,1,2)
plotSpectrum(y6,Fs)
show()
In [ ]: